package com.example.demo.service;

import com.example.demo.dao.TBizArtDAO;
import com.example.demo.dao.TBizShoppingDAO;
import com.example.demo.po.*;
import com.example.demo.util.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class TBizShoppingService {
    @Autowired
    TBizShoppingDAO tBizShoppingDAO;
    @Autowired
    TBizArtDAO tBizArtDAO;

    /**
     * 分页查询接口
     * 这里统一封装了分页请求和结果，避免直接引入具体框架的分页对象, 如MyBatis或JPA的分页对象
     * 从而避免因为替换ORM框架而导致服务层、控制层的分页接口也需要变动的情况，替换ORM框架也不会
     * 影响服务层以上的分页接口，起到了解耦的作用
     * @param pageRequest 自定义，统一分页查询请求
     * @return PageResult 自定义，统一分页查询结果
     */
    public PageResult findByPage(TBizShopping s, PageRequest pageRequest){
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<TBizShopping> list = tBizShoppingDAO.findByParam(s);
        PageResult pageResult = PageUtils.getPageResult(pageRequest, new PageInfo<TBizShopping>(list));
        return pageResult;
    }

    /**
     * 新增
     * @param s
     * @return
     */
    @Transactional
    public boolean save(TBizShopping s){
        int i = tBizShoppingDAO.save(s);
        if(i>0){
            //修改作品状态
            TBizArt art = new TBizArt();
            art.setSalestate("1");
            art.setArtcode(s.getArtId());
            tBizArtDAO.updateByartCode(art);
            return true;
        } else
            return false;
    }


    /**
     * 删除
     * @param id
     * @return
     */
    public boolean del(List<String> id){
        int i = tBizShoppingDAO.del(id);
        if(i>0) {
            return true;
        }else
            return false;
    }

    /**
     * 购物车页面删除商品
     * @param id
     * @return
     */
    @Transactional
    public boolean delShop(String id){
        String[] ids = null;
        if(id.contains(",")){
            ids =id.split(",");
        }else{
            ids=new String[]{id};
        }
        List<String> list = new ArrayList<>();
        for(String a :ids){
            //修改商品状态
            TBizArt art = new TBizArt();
            art.setuType("shop");
            art.setSalestate("0");
            art.setShopId(Integer.valueOf(a));
            int i = tBizArtDAO.editStateByshopId(art);
            if(i>0)
                list.add(a);
        }
        return del(list);
    }




}
